package com.javase.多线程.CompletableFuture;

import java.util.concurrent.*;

/**
 * @author liyanhao
 * @Date 2022-12-05 10:50
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        //创建线程池
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(1, 20, 1l,
                        TimeUnit.SECONDS, new LinkedBlockingQueue<>(50));
        //无返回值 调用默认的线程池
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "-----------come in");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        });
        //无返回值 自定义线程池参数
        CompletableFuture<Void> future2= CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "-----------come in");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, threadPoolExecutor);


        //有返回值 默认线程池
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "---------come in");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 11;
        });

        //有返回值 自定义线程池参数
        CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "---------come in");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 12;
        }, threadPoolExecutor);
        System.out.println(future1.get());
        System.out.println(future2.get());
        System.out.println(future3.get());
        System.out.println(future4.get());

        //关闭线程池
        threadPoolExecutor.shutdown();
        System.out.println(System.currentTimeMillis()-start);

    }
}
